#############################################################################
# Copyright (c) 2009 Dmitry Grushin <dgrushin@gmail.com>.
#
# This file is part of clupower (cluster power manager utility)
#
# Clupower is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Clupower is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Clupower.  If not, see <http://www.gnu.org/licenses/>.
#
# Contributors:
#    Dmitry Grushin <dgrushin@gmail.com> - initial API and implementation
#############################################################################

require 'commands'

class WakeUp
  def initialize
    @wol = WakeOnLan.new
  end

  def wake_wol(id)
    # send wol packet
    mac = Cmd.instance.get_node_mac_address(id)
    sinf = Socket.getaddrinfo(id, nil)
    ip = sinf[0][3]
    @wol.wake(mac, Settings.instance.get('BROADCAST'), ip)
    @wol.close
  rescue SocketError => e
    raise CPE2.new(id).set_cause(e)
  rescue CPRuntimeError => e
    raise CPE13.new(id).set_cause(e)
  end

  def wake_ipmi(id)
    Cmd.instance.execute_cmd(Settings.instance.get('CMD_IPMI_WAKEUP') + " " + id)
  rescue CPExecError => e
    raise CPE13.new(id).set_cause(e)
  end

  def wakeup(id)
    case
    when Settings.instance.get('WAKEUP') == "wol"
      wake_wol(id)
    when Settings.instance.get('WAKEUP') == "ipmi"
      wake_ipmi(id)
    else
      raise CPI2.new(Settings.instance.get('WAKEUP'))
    end
  end
end
